<template>
  <div>
    <div class="test" >test</div>
    <div id="testId">testId</div>
    <!-- <niu-bi> </niu-bi> -->
    <div style="padding-bottom: 20px">
      <!-- <div class="signature-box">
        <VueSignaturePad
          ref="signaturePad"
          :images="[
            { src: 'A.png', x: 0, y: 0 },
            { src: 'B.png', x: 0, y: 10 },
            { src: 'C.png', x: 0, y: 20 },
          ]"
          :options="options"
        />
      </div> -->
    </div>
    <!-- <button @click="undoSignature">撤销</button>
    <button @click="clear">清除</button>
    <button @click="save">保存</button> -->
    <!-- <div style="display: flex;width:1000px;height:500px">
      <div style="width: 50%; height: 100%; border: 1px solid #000;cursor:pointer;">
        <draggable
          v-model="listOne"
          group="site"
          animation="300"
          dragClass="dragClass"
          ghostClass="ghostClass"
          chosenClass="chosenClass"
          :forceFallback="true"
          @start="onStart"
          @end="onEnd"
        >
          <transition-group>
            <div class="item" v-for="item in listOne" :key="item.id">
              <img src="../../assets/images/logo.jpg" alt="logo">
            </div>
          </transition-group>
        </draggable>
      </div>
      <div style="width: 50%; border: 1px solid #000;cursor:pointer;">
        <draggable
          v-model="listTwo"
          group="site"
          animation="100"
          dragClass="dragClass"
          ghostClass="ghostClass"
          chosenClass="chosenClass"
          :forceFallback="true"
          @start="onStart"
          @end="onEnd"
        >
          <transition-group>
            <div class="" style="border:1px solid #red;font-size:20px;width:100px;" v-for="item in listTwo" :key="item.id">
           
               <img src="../../assets/images/logo.jpg" alt="logo" style="width:100%">
            </div>
          </transition-group>
        </draggable>
      </div>
    </div> -->
    <div class="pdfCom">
      <canvas
        :id="'canvas' + item"
        v-for="item in pdfHTML"
        :key="item"
        style="display: block"
      />
    </div>
    <Upload
      action="//"
      :multiple="false"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-error="onError"
      accept=".pdf"
    >
      <Button type="primary">导入PDF</Button>
    </Upload>
    <Button type="primary" @click="changeAnimate">测试动画</Button>
    <transition>
      <div
        v-show="show"
        style="width: 100px; height: 100px; background: skyblue"
      ></div>
    </transition>
  </div>
</template>
 
<script>
// import pdfTest from "@/assets/pdf/test.pdf";
import NiuBi from "../../package/NiuBi/NiuBi.vue";
import draggable from "vuedraggable";
import test from "@/view/multilevel/components/test";
// const pdfTest = require("@/assets/pdf/test.pdf")
import * as pdfjs from "pdfjs-dist";
// const pdfjs = require("pdfjs-dist");
pdfjs.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.entry");
export default {
  components: { NiuBi, draggable, test },
  data() {
    return {
      signature: null,
      options: {
        penColor: "#000",
        dotSize: (1 + 4) / 2,
        minWidth: 1,
        maxWidth: 4,
        throttle: 16,
        minDistance: 5,
        backgroundColor: "rgba(0,0,0,0)",
        velocityFilterWeight: 0.5,
        onBegin: () => {},
        onEnd: () => {},
      },
      listOne: [
        { id: 1, name: "www.itxst.com" },
        { id: 2, name: "www.jd.com" },
        { id: 3, name: "www.baidu.com" },
        { id: 4, name: "www.taobao.com" },
      ],
      listTwo: [
        { id: 5, name: "www.google.com" },
        { id: 6, name: "www.msn.com" },
        { id: 7, name: "www.ebay.com" },
        { id: 8, name: "www.yahoo.com" },
      ],

      imgFiles: [],
      pageNo: null,
      pdfPageNumber: null,
      pdfTotalPages: 1,
      renderingPage: false,
      pdfData: null, // PDF的base64
      scale: 1.5, // 缩放值

      pdfDoc: null, // pdfjs 生成的对象
      pdfHTML: 0, // pdfjs 生成的对象
      show: true,
    };
  },
  mounted() {
    console.log(this.$route)
    console.time()
    let num  = 0
    for (let index = 0; index < 100000; index++) {
      num++
    }
    console.timeEnd();
    let dom = document.querySelector('.test')
    let dom2 = document.querySelector('#testId')
    console.log(dom,dom2);
    // this.init('https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf');
    // let data = [
    //   {
    //     name: "颜色",
    //     specs: [{value:"白色"}, {value:"黑色"}],
    //   },
    //   {
    //     name: "尺寸",
    //     specs: [{value:"14寸"}, {value:"15寸"}, {value:"16寸"}],
    //   },
    //   {
    //     name: "处理器",
    //     specs: [{value:"i5"}, {value:"i7"}, {value:"i9"}],
    //   },
    // ];
    let data = [
      {
        name: "颜色",
        specs: ["白色", "黑色"],
      },
      {
        name: "尺寸",
        specs: ["14寸", "15寸", "16寸"],
      },
      {
        name: "处理器",
        specs: ["i5", "i7", "i9"],
      },
    ];
    // function combine(arr) {
    //   let result = [[]];//定义一个数组必须要有一项（且这一项必须是数组）
    //   arr.map((x) => {
    //     let res = [];
    //     console.log(result,'result');
    //     result.map((y) => {
    //       x.specs.map((z) => {
    //         //最内层循环x.specs.map第一次执行完之后res的值就是[["白色"], ["黑色"]]，因为specs的值为两项["白色", "黑色"]循环两遍，循环完后跳出循环到上一层循环，
    //         //此时上一层的循环result.map的result还是[[]],所以执行完一遍之后跳出当前循环到上一层循环，
    //         //此时arr.map循环完第一遍开始赋值将result = res，此时result为[["白色"], ["黑色"]]，然后开始进入result.map循环
    //         //此时x.specs.map的值为arr.map的第二次循环也就是循环["14寸","15寸", "16寸"]，而result.map为[["白色"], ["黑色"]]，
    //         //此时循环的步骤为result.map第一遍循环result，此时y为["白色"]，而z为arr第二项的specs里面的每一项，于是用["白色"]去拼接["14寸","15寸", "16寸"]的每一项
    //         //此时就res就变成了result.map[["白色"], ["黑色"]]跟["14寸","15寸", "16寸"]去按顺序一项一项的去组合，组合完之后将 result = res，
    //         //以此类推便出现了最终的所有值的组合结果，很巧妙的一个套路，自己去从0开始写还是比较费脑筋的，尤其逻辑处理能力尚不强的时候以及没多少经验的时候
    //         res.push([...y, z]);
    //       });
    //     });
    //     result = res;//将第一次循环之后的值赋值给result，此时result为[["白色"], ["黑色"]]，故下一波循环得循环两次
    //   });
    //   return result;
    // }
    // console.log(combine(data));

    const generateCombinations = (arr, result = [], current = {}, i = 0) => {
      // 由于arr.length的长度一般都不会等于，所以最开始直接执行else
      // 第二次函数调用i等于1，而数组长度依旧为3，所以还是执行else
      // 第三次函数调用，此时i等于2，数组长度依旧为3，所以还是执行else
      // 第四次函数调用，此时i等于3，i已经等于数组长度了，故执行if，此时current为，i5 {颜色: '白色', 尺寸: '14寸', 处理器: 'i5'}，
      // 当第四次函数调用完之后执行return result,但是函数之前的循环并没有终止掉，上一步的循环停留在调用递归的地方
      // 而此时函数执行到处理器规格的specs循环的第二遍,此时current等于i7 {颜色: '白色', 尺寸: '14寸', 处理器: 'i7'}，i还是之前的没有加一的i所以为2
      // 于是再次执行又要递归i再次加1等于3
      // 后面就不解释了，直接看打印值，很巧妙的一种方法，理解起来稍微有点绕不如笛卡尔积写法
      if (i === arr.length) {
        // console.log("执行push");
        result.push({ ...current });
      } else {
        for (const value of arr[i].specs) {
          // 第一次循环（此处第一次循环为颜色规格的specs第一次循环）current[arr[i].name]的arr[i].name值为:'颜色',而value为颜色规格的每一项，
          // 此时循环第一次之后arr不变，result不变，current为 白色 {颜色: '白色'},i+1等于1，然后执行递归
          // 第二次循环，由于执行了递归，第二次循环变成了循环尺寸规格的specs，
          // 此时current为 14寸 {颜色: '白色', 尺寸: '14寸'},i+1等于2，然后再次递归，
          // 第三次循环，由于执行了递归，第三次循环变成了循环处理器规格的specs，
          // 此时current为 i5 {颜色: '白色', 尺寸: '14寸', 处理器: 'i5'},i+1等于3，然后再次递归，
          current[arr[i].name] = value;
          // console.log(arr[i].name, "----", value, current, i);
          generateCombinations(arr, result, current, i + 1);
        }
      }
      return result;
    };
    // console.log(generateCombinations(data));
  },
  methods: {
    changeAnimate() {
      this.show = !this.show;
      if (this.show) {
        this.animateType = "rotateInUpLeft";
      } else {
        this.animateType = "rotateOutDownRight";
      }
      // setTimeout(()=>{
      //   this.show = true
      // },2000)
    },

    onStart() {
      this.drag = true;
    },
    onEnd() {
      this.drag = false;
    },
    // 撤销上一步
    undoSignature() {
      this.$nextTick(() => {
        this.$refs.signaturePad.undoSignature();
      });
    },
    // 清除
    clear() {
      this.$nextTick(() => {
        this.$refs.signaturePad.clearSignature();
      });
    },
    // 保存
    save() {
      this.$nextTick(() => {
        const signatureData = this.$refs.signaturePad.saveSignature();
        console.log(signatureData);
      });
    },

    beforeUpload(file) {
      console.log(file, "ee");
      console.log(URL.createObjectURL(file), "11");
      // this.init('https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf');
      // this.convertToBase64(e);
      // const fileReader = new FileReader();
      // fileReader.readAsArrayBuffer(e);
      // fileReader.onload = () => {};
      this.init(URL.createObjectURL(file));
      // return new Promise((resolve, reject) => {
      //   const fileReader = new FileReader();

      //   fileReader.onload = () => {
      //     const arrayBuffer = fileReader.result;
      //     const fileStream = new Blob([arrayBuffer], {
      //       type: "application/pdf",
      //     });

      //     // 在这里可以使用fileStream作为文件流进行后续操作
      //     console.log("文件流：", fileStream);

      //     const fileUrl = URL.createObjectURL(fileStream);
      //     console.log("fileUrl", fileUrl);
      //     // this.resolvePdf('https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf');
      //     // this.resolvePdf(fileUrl);
      //     this.init(fileUrl);

      //     // 将fileStream作为参数传递给resolve，继续上传文件
      //     resolve(fileStream);
      //   };

      //   fileReader.readAsArrayBuffer(file);
      // });
    },
    onSuccess(e) {
      console.log(e, "success");
    },
    onError(e) {
      console.log(e, "error");
    },
    convertToBase64(file) {
      let reader = new FileReader();
      reader.onloadend = () => {
        let base64Data = btoa(reader.result);
        console.log("base64Data");
        this.pdfData = base64Data;
        this.$nextTick(() => {
          this.handlePdf();
        });
      };
      reader.readAsBinaryString(file);
    },
    resolvePdf(url) {
      console.log("调用");
      const loadingTask = pdfjs.getDocument(url);
      console.log(loadingTask, "loadingTask");
      loadingTask.promise
        .then(
          (pdf) => {
            console.log(pdf, "pdf成功");
            state.pdfCtx = pdf;
            state.pageNum = pdf.numPages;
          },
          (err) => {
            console.log(err, "err");
          }
        )
        .catch((err) => {
          console.log(err, "err");
        });
    },
    init(fileUrl) {
      console.log(fileUrl, "fileUrl");
      let _this = this;
      pdfjs
        .getDocument(fileUrl)
        .then((fileContent) => {
          console.log(fileContent, "fileContent");
          _this.pdfDoc = fileContent;
          _this.pdfHTML = fileContent.numPages;
          setTimeout(() => {
            _this.renderPage(fileContent.numPages);
          }, 100);
        })
        .catch((err) => {
          console.log(err, "errerrerrerrerr");
        });
    },
    renderPage(nums) {
      for (let item = 1; item <= nums; item++) {
        // 获取页面canvas节点
        let canvas = document.getElementById(`canvas${item}`);
        // 获取上下文
        const ctx = canvas.getContext("2d");
        // 获取每一页的内容
        this.pdfDoc.getPage(item).then((page) => {
          // 文件页面的视图 1倍
          const viewport = page.getViewport(1);
          // 将画布宽度设置为视图宽度
          canvas.width = viewport.width;
          canvas.height = viewport.height;

          const renderContext = {
            canvasContext: ctx,
            viewport: viewport,
          };
          console.log(renderContext);
          // 渲染页面内容：参数是canvas画布上下文，以及文件视图
          page.render(renderContext).then((res) => {
            console.log(canvas.toDataURL("image/png"), "canvas.toDataURL");
            const img = document.createElement("img");
            img.src = canvas.toDataURL("image/png");
            document.body.appendChild(img);
          });
        });
      }
    },
  },
  watch: {
     options:{
      
     }
  },
  render(h){
    this.$nextTick
    console.log('zhixing');
    return h('div', 'haha')
  }
};
</script>
<style scoped lang="less">
.signature-box {
  width: 100%;
  height: 360px;
  border: 1px solid #dedede;
}
.dragClass {
  border: 5px solid #641c1c !important;
}
.ghostClass {
  border: 5px solid #1831a0 !important;
}
// .chosenClass{
//   border: 5px solid #16da9f !important;
// }
.v-enter {
  opacity: 0;
}

.v-enter-active {
  transition: opacity 1s;
}
.v-leave-to {
  opacity: 0;
  transform: scale(0.1) translate(-100%, 0);
}

.v-leave-active {
  transition: opacity 1s;
  transform: scale(1) translate(0, 0);
}
</style>
